const { exec } = require('../db/mysql')
const xss = require('xss')

const getList = (author = "", keyword = "") => {
  let sql = `select 
  id,
  title,
  author,
  date_format(createtime, '%Y-%c-%d %H:%i:%s' ) as createtime
  from blogs where 1=1 and status=1
  `
  if (author) {
    sql += ` and author like '%${author}%'`
  }
  if (keyword) {
    sql += ` and title like '%${keyword}%'`
  }
  return exec(sql)
};
const getDetail = async (id = "") => {
  const sql = `select * from blogs where id='${id}' and status=1`
  if (id) {
    const res = await exec(sql)
    if (res.length) {
      return res[0]
    } else {
      return null
    }
  } else {
    return new Promise(resolve => resolve(null))
  }
};
const newBlog = (title, content, author) => {
  const sql = `insert into blogs (title,content,author) values ('${xss(title)}','${xss(content)}','${author}')`
  return exec(sql).then(insertData => {
    return insertData.insertId
  })
};
const updateBlog = (title, content, id, author, isAdmin = 0) => {
  let sql = `update blogs set title='${xss(title)}',content='${xss(content)}' where id='${id}'`
  if (!isAdmin) {
    // 非管理员只能编辑自己的
    sql += `and author='${author}'`
  }
  return exec(sql).then(updateData => {
    return updateData.affectedRows
  })
};
const deleteBlog = (id, author, isAdmin = 0) => {
  // const sql = `delete from blogs where author='${author}' and id='${id}'`
  // 逻辑删除
  const sql = `update blogs set status=0 where id='${id}'`
  if (!isAdmin) {
    // 非管理员只能删除自己的
    sql += `and author='${author}'`
  }
  return exec(sql).then(delData => {
    return delData.affectedRows
  })
};
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog,
};
